'use strict'

const Controller = require('egg').Controller
const Joi = require('@hapi/joi')
const _ = require('lodash')
const uuidv4 = require('uuid/v4')

class RefreshController extends Controller {
  /**
   * 刷新微信token
   */
  async RefreshWxToken() {
    const { ctx, service, app } = this
    const { config: wechatConfig } = app.config.wechat
    const { wxAppToken } = service

    try {
      const tokenArr = ['mina_rider', 'public_wx']

      for (let i = 0; i < tokenArr.length; i++) {
        const appName = tokenArr[i]

        const configObj = wechatConfig[appName]
        if (!configObj) throw `暂无 ${appName} token config`

        const apiRes = await wxAppToken.getApiToken(
          configObj.appId,
          configObj.appSecret
        )

        console.log('apiRes', apiRes)

        wxAppToken.upsert({
          app_name: appName,
          appid: configObj.appId,
          access_token: apiRes.access_token,
          expires_in: apiRes.expires_in
        })
      }

      ctx.success()
    } catch (err) {
      ctx.fail(err)
    }
  }
}

module.exports = RefreshController
